<?php
/*
File description

This file is invoked from the following pages:
	-admin.php
	-user.php

This script uses a if, elseif, else layout to handle all POST cases which are called from one of the pages.

The first case checks for a user change from user.php.  This means that if a user makes a crowdsourced change in user.php, this script will be called using POST,
in which case this script will catch on that specific condition, and proceed to either a) auto commit that change if the user has auto commit rights, or b) create
a log file to remember the pre-change state, and then store the change for further admin approval.

The second and third cases are called from admin.php.  For the accept clause, the admin from admin.php will click an accept button which will call a POST method to
this page in which the condition will catch and proceed to commit the change and delete the now futile log file.  If the admin presses deny, then the 3rd elseif condition in 
this script will catch, in which the log file will be restored into the main OCR file, and then we will delete the log file.

The 4th condition that catches in this script is called from admin.php, in which the admin desires to change the main directory of the OCR files. 

The final condition, or default action of the script, is to redirect to a safe location, searcSholem.cgi which serves as a home page for this program. 
*/


session_start(); //Begin the session to receive logged in status and user info
require_once "globals.php"; //Needed to access log files and OCR files
require_once "utility.php"; //Needed for remote server commands


//Check for logged in status, if not, redirect to log in page.
if($_SESSION["logged_in"] == false ){
    header("Location: sholem_login.php");
    exit;
}


//This condition will catch if a user makes a editing change from user.php.  This condition is caught after user.php calls validate.php (this file) using a POST redirect of information.
//Upon catching from user.php, this block of control will store an old copy of the pre-edited text into our logs, updating the new version to the edited version, and lastly compare the 
//two previously mentioned files via a diff command.
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ocrMakeChange']) ){

	//This is the exact OCR file that we wish to update and change
	$locationOfOcrFile = $locationOfAllOcrFiles."/".$_POST['book']."/".$_POST['page'];
	
	//Now take the entire text that was modified (crowdsourced) by the user
	$textChangeFromUser = $_POST['editedText'];
	
	
	//If the user who made the change has status 1 or 2, then that means the admin has approved this user for auto-commit (ie no admin needs to individually approve their changes, since they are trusted)
	if ($_SESSION['permission'] == 1 || $_SESSION['permission'] == 2){
		//Replace the main repo OCR file with the newly modified text
		file_put_contents($locationOfOcrFile, $textChangeFromUser);

		//Nav to the OCR directory, commit the file to SVN, Put user name in comment
		$command = "cd ".$locationOfAllOcrFiles."/".$_POST['book']."; svn commit ".$_POST['page']." -m '".$_POST['user']."'"; 
		
		//Perform the commit to the main repo
		executeRemoteCommand($command);

		$msg = "Change approved and commited.";
		//Leave this script and return back to user.php, since the user may want to make another change
		exit(header("Location:user.php?book=".$_POST['book']."&page=".$_POST['page']."&msg=".$msg));
	}
	//Otherwise, the user changes will have to be approved by the admin himself, meaning we must create a log file
	else{

		//Make a new text file of format "userEditsBookPageAtTime", which is comprised of the contents of the file before the user made any changes. In other words, the log file which stores
		//the pre-edited file is renamed to explain who edited it, what file was edited, and at what time
		$preEditFileName = "_".$_POST['user']."~".$_POST['book']."~".$_POST['page']."~".time();
		
		//Save the pre-edited version of the file into our logs directory
		$readOcrFile = file_get_contents($locationOfOcrFile);
		
		//Check for error in file opening, print attempted file to open
		if (!$readOcrFile){
			echo "<br> Failure: cannot open OCR file ".$locationOfOcrFile."<br>";
			sleep(10);
		}
		//Otherwise, the file opened successfully
		else{
			//Store the pre-edited version of the OCR file into the logs. If the admin denies the change, this log file will be the restored as the main copy of the OCR file
			file_put_contents($locationOfLogFiles."/".$preEditFileName, $readOcrFile);

			//Get the text that was just edited by the user.  This comes from the textarea in user.php 
			$textChangeFromUser = $_POST['editedText'];
			
			//Replace the main repo OCR file with the newly edited text
			file_put_contents($locationOfOcrFile, $textChangeFromUser);
			
			//Now we have 2 files.  The old file (pre-edit without changes) and the new file (post-edit with changes) 
			//Run a diff command on the old file versus the newly edited file. This will give us the exact change(s) made. Save as a diff file
			$command = "diff ".$locationOfOcrFile." ".$locationOfLogFiles."/".$preEditFileName." > ".$locationOfLogFiles."/".$preEditFileName."~diff"; 
			//$command1 = "diff ".$locationOfLogFiles."/".$preEditFileName." ".$locationOfOcrFile." > ".$locationOfLogFiles."/".$preEditFileName.".patch"; 
			$command1 = "diff -u ".$locationOfOcrFile." ".$locationOfLogFiles."/".$preEditFileName." > ".$locationOfLogFiles."/".$preEditFileName.".patch"; 
			//Execute on the server remotely
			echo executeRemoteCommand($command);
			echo executeRemoteCommand($command1);

			$msg = "Change awaiting approval by Dr. Finkel";
			//Leave this script and return back to user.php, since the user may want to make another change
			exit(header("Location:user.php?book=".$_POST['book']."&page=".$_POST['page']."&msg=".$msg));
		}
	}
}


//Admin has approved of crowdsourced change, now we commit that change
elseif ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['commitOcrChange'])){

	//Create the name of the log files we wish to delete, since we have just commited the newest (current) version 
	$locationOfIndividualLogFile = $locationOfLogFiles."/".$_POST['user']."~".$_POST['book']."~".$_POST['page']."~".$_POST['time'];
	
	//Apply the patch
	//$command = "cd ".$locationOfAllOcrFiles."/".$_POST['book'].";  patch  < ".$locationOfIndividualLogFile.".patch";  //Be mindful of this line, very strange...sometimes .patch suffix shows up, sometimes not. Probably traced back to parseLogFiles() or admin presentation of log files 
	//echo $command."<br>";
	//executeRemoteCommand($command);
	
	//Perform the commit to the main repo
	$command ="cd ".$locationOfAllOcrFiles."/".$_POST['book']."; svn commit ".$_POST['page']." -m '".$_POST['user']."'"; //Put user name in comment
	executeRemoteCommand($command);

	//Remove the log files containing older version of this OCR file; it can be safely removed since the admin has permanently approve it
	executeRemoteCommand("rm ".$locationOfIndividualLogFile." ".$locationOfIndividualLogFile."~diff ".$locationOfIndividualLogFile.".patch");
	
	$Msg = "Admin has approved a change";
	//Return to admin page
	exit(header('Location: admin.php?msg='.$Msg));    
}


//Deny the most recent crowdsourced change
elseif ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['denyOcrChange'])){

	//The admin has denied a change. Therefore we need to restore the older log file as the current version, and then delete those files sinced they've served their purpose

	//perform patch agaisnt the current OCR versus the original preEdit file.  this will provide 
	//patch -R < hello.patch
	

	//Get the log file associated with earlier pre-edited versions of this OCR file
	$locationOfIndividualLogFile = $locationOfLogFiles."/".$_POST['user']."~".$_POST['book']."~".$_POST['page']."~".$_POST['time'];

	//Now restore the current OCR file with the older log version
	//file_put_contents(file_get_contents("constants/ocrFilesPath.txt")."/".$_POST['book']."/".$_POST['page'], file_get_contents($locationOfLogFile));
	//Reverse the patch
	$command = "cd ".$locationOfAllOcrFiles."/".$_POST['book'].";  patch -Nu < ".$locationOfIndividualLogFile.".patch";  
	echo $command."<br>";
	executeRemoteCommand($command);
	
	
	
	//Remove the log files, since they just restored themselves as the newest most up-to-date version
	executeRemoteCommand("rm ".$locationOfIndividualLogFile." ".$locationOfIndividualLogFile."~diff ".$locationOfIndividualLogFile.".patch");

	$Msg = "Admin has denied a change";
	//Return to admin page
	exit(header('Location: admin.php?msg='.$Msg));    
} 


//Set the new path of the OCR files you want crowdsourced
elseif ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ocrFilesPath'])){

	//Set a new path for the OCR files, see utility.php for more documentation on this function call
	setOcrFilesPath($_POST['ocrFilesPath']);

	$msg = "New OCR files directory set.";

	//Return to admin page
	header('Location: admin.php?msg='.$msg);    
	exit;
} 

//The default case of this page is to return to entry page for the site, the search page
else{
	header('Location: sholem_login.php');    
	exit;
}

















?>